﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using VSTranslator.Translation;

namespace VSTranslator.Settings
{
	public partial class OptionsPageControl : UserControl
	{
		private OptionsPage optionsPage;

		/// <summary>
		/// Gets or Sets the reference to the underlying OptionsPage object.
		/// </summary>
		public OptionsPage OptionsPage
		{
			get
			{
				return optionsPage;
			}
			set
			{
				optionsPage = value;
				InitView();
			}
		}

		private BaseTranslator Translator
		{
			get { return (BaseTranslator)cmbService.SelectedItem; }
		}

		public OptionsPageControl()
		{
			InitializeComponent();
		}

		private void InitView()
		{
			foreach (BaseTranslator t in TranslatorRegistry.Translators)			
				cmbService.Items.Add(t);
			cmbService.SelectedItem = TranslatorRegistry.Translators.Find(t => t.Name == OptionsPage.TranslationService);
			FillLanguages();
		}

		private void FillLanguages()
		{
			BaseTranslator t = Translator;            
            FillLanguageList(cmbSourceLanguage, t.SourceLanguages, OptionsPage.SourceLanguage);
            FillLanguageList(cmbTargetLanguage, t.TargetLanguages, OptionsPage.TargetLanguage);            
		}

		private void FillLanguageList(ComboBox cb, List<TranslationLanguage> langs, string selectedCode)
		{
			cb.Items.Clear();
            foreach (TranslationLanguage l in langs) {
                cb.Items.Add(l);
            }
            if (langs.Count != 0) {
                cb.SelectedItem = langs.Find(l => l.Code == selectedCode) ?? langs[0];
            }
			UpdateSwap();
		}

		private void UpdateSwap()
		{
			TranslationLanguage source = (TranslationLanguage)cmbSourceLanguage.SelectedItem;
			TranslationLanguage target = (TranslationLanguage)cmbTargetLanguage.SelectedItem;
			cmdSwap.Enabled = source != null && target != null && Translator.CanSwap(source.Code, target.Code);
		}

		public void UpdateOptions()
		{
			OptionsPage.TranslationService = Translator.Name;
			OptionsPage.SourceLanguage = (cmbSourceLanguage.SelectedItem as TranslationLanguage).Code;
			OptionsPage.TargetLanguage = (cmbTargetLanguage.SelectedItem as TranslationLanguage).Code;
		}

		//events
		private void cmbService_SelectedIndexChanged(object sender, EventArgs e)
		{
			FillLanguages();
		}	

		private void cmdSwap_Click(object sender, EventArgs e)
		{
			TranslationLanguage source = (TranslationLanguage)cmbSourceLanguage.SelectedItem;
			TranslationLanguage target = (TranslationLanguage)cmbTargetLanguage.SelectedItem;
			cmbSourceLanguage.SelectedItem = Translator.SourceLanguages.Find(l => l.Code == target.Code);
			cmbTargetLanguage.SelectedItem = Translator.TargetLanguages.Find(l => l.Code == source.Code);			
		}

		private void cmbLanguage_SelectedIndexChanged(object sender, EventArgs e)
		{
			UpdateSwap();
		}

	}
}
